package com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.fans;

import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.alibaba.android.arouter.launcher.ARouter;
import com.kaiwukj.android.mcas.di.component.AppComponent;
import com.kaiwukj.android.ufamily.R;
import com.kaiwukj.android.ufamily.app.base.review.BaseMvpFragment;
import com.kaiwukj.android.ufamily.app.constant.ARouterUrlKt;
import com.kaiwukj.android.ufamily.di.component.DaggerDynamicComponent;
import com.kaiwukj.android.ufamily.di.module.DynamicModule;
import com.kaiwukj.android.ufamily.mvp.http.entity.result.FansResult;
import com.kaiwukj.android.ufamily.mvp.ui.page.dynamic.DynamicContract;
import com.kaiwukj.android.ufamily.mvp.ui.widget.SpaceItemDecoration;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.List;

import butterknife.BindView;

public class FansFragment extends BaseMvpFragment<FansPresenter> implements DynamicContract.FansView {

    @BindView(R.id.refresh_layout)
    SmartRefreshLayout refreshLayout;
    @BindView(R.id.rv_list)
    RecyclerView rvList;
    @BindView(R.id.empty_view)
    QMUIEmptyView emptyView;

    private FansAdapter mAdapter;

    private int pageSize = 12;

    private int type;
    private int userId;

    private boolean isLoadingMore = false;
    private int eventPos = -1;

    public static FansFragment newInstance(int type, int userId) {
        FansFragment fansFragment = new FansFragment();
        fansFragment.type = type;
        fansFragment.userId = userId;
        return fansFragment;
    }

    @Override
    public void setupFragmentComponent(@NonNull AppComponent appComponent) {
        super.setupFragmentComponent(appComponent);
        DaggerDynamicComponent.builder()
                .appComponent(appComponent)
                .dynamicModule(new DynamicModule(this))
                .build().inject(this);
    }

    @Override
    protected int getLayoutId() {
        return R.layout.widget_list_normal;
    }

    @Override
    protected void initView() {
        refreshLayout.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                isLoadingMore = true;
                loadData(false);
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                loadData(true);
            }
        });

        rvList.setLayoutManager(new LinearLayoutManager(getContext()));
        rvList.addItemDecoration(new SpaceItemDecoration(1));
        mAdapter = new FansAdapter();

        if (userId < 0) {
            userId = getApp().getUserInfo().getId();
            mAdapter.setIsOwner(true);
        }
       /* mAdapter.setOnItemClickListener((adapter, view, position) -> {
            switch (view.getId()) {
                case R.id.container_attention:
                    showMessage("关注");
                    break;
                case R.id.btn_attention:
                    showMessage("取消关注");
                    break;
            }

        });*/
        mAdapter.setOnItemChildClickListener((adapter, view, position) -> {
            int eventId = type == 1 ? mAdapter.getItem(position).getBeConcernId() : mAdapter.getItem(position).getConcernId();
            if (view.getId() == R.id.iv_avatar) {
                ARouter.getInstance().build(ARouterUrlKt.DynamicPersonUrl)
                        .withInt("userId", eventId)
                        .navigation();
            }
        });
        mAdapter.setOnAttentionListener((pos, attention) -> {
            int eventId = type == 1 ? mAdapter.getItem(pos).getBeConcernId() : mAdapter.getItem(pos).getConcernId();
            if (!attention) {
                eventPos = pos;
                mPresenter.attention(eventId);
            } else {
                showMessageOKCancel(getActivity(), "是否不再关注TA", v -> {
                    eventPos = pos;
                    mPresenter.cancelAttention(eventId);
                });
            }
        });
        rvList.setAdapter(mAdapter);
        if (type == 1) {
            mAdapter.setAttention();
        }
    }

    @Override
    protected void initData(Bundle savedInstanceState) {
    }

    @Override
    protected void initDataSupport() {
        super.initDataSupport();
        loadData(true);
        emptyView.show(true);
    }

    private void loadData(boolean isRefresh) {
        if (type == 2) {
            mPresenter.fetchFans(userId, isRefresh ? 0 : (int) mAdapter.getLastItemId(), pageSize);
        } else {
            mPresenter.fetchAttention(userId, isRefresh ? 0 : (int) mAdapter.getLastItemId(), pageSize);
        }
    }

    @Override
    public void onFetchFans(List<FansResult> results, int totalCount) {
        emptyView.hide();
        if (isLoadingMore) {
            isLoadingMore = false;
            mAdapter.addData(results);
            if (pageSize > results.size()) {
                refreshLayout.finishLoadMoreWithNoMoreData();
            } else {
                refreshLayout.finishLoadMore();
            }
        } else {
            refreshLayout.finishRefresh();
            mAdapter.setList(results);
        }
        if (onAttentionChangedEvent != null)
            onAttentionChangedEvent.onChanged(totalCount, type);
        showEmptyView();
    }

    @Override
    public void onTaskErr(int taskId) {
        super.onTaskErr(taskId);
        emptyView.hide();
        if (isLoadingMore) {
            isLoadingMore = false;
            refreshLayout.finishLoadMore(false);
        } else {
            refreshLayout.finishRefresh(false);
        }
        showEmptyView();
        eventPos = -1;
    }

    @Override
    public void onTaskSuccess(int taskId) {
        super.onTaskSuccess(taskId);
        if (taskId == FansPresenter.ATTENTION_CANCEL) {
            //  if (type == 1 && userId == getApp().getUserInfo().getId()) {
            // mAdapter.postCancelAttention(eventPos);
            // } else {
            mAdapter.postCancelAttention(eventPos);
            // }
            updateFansCount();
            eventPos = -1;
        } else if (taskId == FansPresenter.ATTENTION) {
            mAdapter.postAttention(eventPos);
            eventPos = -1;
            updateFansCount();
        }
    }

    private void updateFansCount() {
        if (onAttentionChangedEvent != null) {
            onAttentionChangedEvent.onChanged(getApp().getUserInfo().getConcernNum(), 1);
        }
    }

    private void showEmptyView() {
        if (mAdapter != null && mAdapter.getItemCount() == 0) {
            emptyView.show("暂没有数据", "");
        }
    }

    public OnAttentionChangedEvent onAttentionChangedEvent;

    public void setOnAttentionChangedEvent(OnAttentionChangedEvent onChangedEvent) {
        this.onAttentionChangedEvent = onChangedEvent;
    }

    public interface OnAttentionChangedEvent {
        void onChanged(int count, int type);
    }
}
